package com.qf.utils.filter;

import com.qf.bean.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * IntelliJ IDEA -> person
 * 2019/11/20 0:54
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter开始在执行");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");
        String requestURI = request.getRequestURI();
        System.err.println("url:"+requestURI);
        if (requestURI.endsWith("login.jsp")|| requestURI.endsWith("login") || requestURI.endsWith("/") ||
                requestURI.endsWith(".ico")|| requestURI.contains("/img")|| requestURI.contains("/css")){
            filterChain.doFilter(servletRequest,servletResponse);
        }
        else {
            HttpSession session = request.getSession();
                Employee employee = (Employee) session.getAttribute("employee");
                if (employee != null){
                    System.out.println("name:"+employee.getLoginname());
                    filterChain.doFilter(servletRequest,servletResponse);
            }
            else {
                PrintWriter out = response.getWriter();
                out.print("<script>alert('请先登录！');location.href='/login.jsp';</script>");
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter结束执行");
    }
}
